package bb.lanxing.mvp.presetner;

import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import bb.lanxing.activity.interfaces.IProModel;
import bb.lanxing.util.extender.KotlinExtender;
import bb.lanxing.model.database.ProPerms;
import bb.lanxing.model.json.ServerCodeJson;
import bb.lanxing.network.ApiRequestBuilder;
import bb.lanxing.network.NetSubscribe;
import rx.Observable;
import rx.schedulers.Schedulers;

public class ProModelImpl implements IProModel {
    @Override
    public Observable<ProPerms> getProInfo() {
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("t", System.currentTimeMillis());
        return Observable.create(new NetSubscribe(ApiRequestBuilder.wwwget("goods/pro/49/perms/", hashMap))).subscribeOn(Schedulers.io()).flatMap(str -> {
            ServerCodeJson serverCodeJson = (ServerCodeJson) JSON.parseObject(str, ServerCodeJson.class);
            if (serverCodeJson.getCode() != 0) {
                return Observable.error(new IllegalStateException("request settings result failed"));
            }
            if (serverCodeJson.getData() != null) {
                try {
                    ProPerms proPerms = new ProPerms(new JSONObject(serverCodeJson.getData()));
                    KotlinExtender.INSTANCE.deleteAll(ProPerms.class);
                    proPerms.save();
                    return Observable.just(proPerms);
                } catch (JSONException e) {
                    return Observable.error(new IllegalStateException("ProPerms is null"));
                }
            }
            return Observable.error(new IllegalStateException("ProPerms is null"));
        });
    }
}
